package controller.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;

import model.entity.product.Brand;

import com.google.gson.Gson;

import controller.UploadContr;

import dao.JPAHiberDAOFactory;
import dao.entity.BrandDAO;

/**
 * Servlet implementation class BrandContr
 */
public class BrandContr extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BrandDAO brandDAO;

	public BrandContr() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		brandDAO = JPAHiberDAOFactory.getInstance().getBrandDAO();
		List<Brand> brList = brandDAO.selectAll();

		for (Brand brand : brList) {
			brand.setProducts(null);
			
		}

		Gson gson = new Gson();
		String objectToTransfer = gson.toJson(brList);

		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print(objectToTransfer);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String commnad = request.getParameter("command");
		brandDAO = JPAHiberDAOFactory.getInstance().getBrandDAO();

		if (commnad != null) {
			// Get json string from request
			String jsonObj = "";
			Map<String, String[]> paras = request.getParameterMap();
			for (Entry<String, String[]> e : paras.entrySet()) {
				String[] temp = e.getValue();
				if (temp[0].equals(""))
					jsonObj = e.getKey();
			}

			// Chuyen du lieu sang POJO
			Gson gson = new Gson();
			Brand thisBrand = gson.fromJson(jsonObj, Brand.class);


			if (commnad.equals("create")) {
				brandDAO.persist(thisBrand);

				response.setContentType("application/json");
				PrintWriter out = response.getWriter();
				out.print(gson.toJson(thisBrand));

			} else if (commnad.equals("delete")) {
				//Delete trong data
				brandDAO.deleteByID(thisBrand.getBrandId());
				//Delete hinh
				String path = request.getSession().getServletContext().getRealPath("/") + thisBrand.getLogo();
				UploadContr.deleteFile(path);
			} else if (commnad.equals("update")) {
				Brand dbBrand = brandDAO.findReference(thisBrand.getBrandId());
				brandDAO.refresh(dbBrand);
				dbBrand.setDescription(thisBrand.getDescription());
				dbBrand.setLogo(thisBrand.getLogo());
				dbBrand.setName(thisBrand.getName());

				brandDAO.persist(dbBrand);
			}
		} else {
			String path = request.getSession().getServletContext().getRealPath("/") + "upload/brands";
			HashMap<String, String> para = UploadContr.processOneUploadByID(request, path);
			
			Brand brand = brandDAO.findReference(Integer.parseInt(para.get("id")));
			brand.setLogo("upload/brands/"+FilenameUtils.getName(para.get("file")));
			brandDAO.persist(brand);
			request.setAttribute("ok", "ok");
			//request.getRequestDispatcher("manager/testGridR.jsp").forward(request, response);
			response.sendRedirect(para.get("returnLink"));
		}
	}

}
